import json

from django import http
from django.core.paginator import Paginator, EmptyPage

from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from django.views import View
from django_redis import get_redis_connection

from contents.utils import index_category
from goods.models import GoodsCategory, SKU, GoodsVisitCount
from goods.utils import get_breadcrumb, hot_order
from meiduo.utils.mixn import AuthenticateView
from meiduo.utils.response_code import RETCODE


class ListView(View):
    def get(self,request,category_id,page_num):
        # return http.HttpResponseForbidden("nihao")
        # 获取到三级对象
        cat3=GoodsCategory.objects.get(id=category_id)
        sort=request.GET.get("sort","")
        if sort=="price":
            sorts="-price"
        elif sort=="hot":
            sorts = "-sales"
        else:
            sort='default'
            sorts="-create_time"

        sku = cat3.sku_set.filter(is_launched=True).order_by(sorts)
        paginator = Paginator(sku, 5)
        page_skus = paginator.page(page_num)
        num_pages=paginator.num_pages
        context = {
            'categories': index_category(),  # 频道分类
            'breadcrumb': get_breadcrumb(cat3),  # 面包屑导航
            'sort': sort,  # 排序字段
            'category': cat3,  # 第三级分类
            'page_skus': page_skus,  # 分页后数据
            'total_page': num_pages,  # 总页数
            'page_num': page_num  # 当前页码
        }
        return render(request, 'list.html', context)
class HotView(View):
    def get(self,request,category_id):
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'hot_skus': hot_order(category_id)})

class DetailView(View):
    """商品详情界面"""

    def get(self, request, sku_id):

        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        category = sku.category  # 获取当前sku所对应的三级分类

        # 查询当前sku所对应的spu
        spu = sku.spu

        """1.准备当前商品的规格选项列表 [8, 11]"""
        # 获取出当前正显示的sku商品的规格选项id列表
        current_sku_spec_qs = sku.specs.order_by('spec_id')
        current_sku_option_ids = []  # [8, 11]
        for current_sku_spec in current_sku_spec_qs:
            current_sku_option_ids.append(current_sku_spec.option_id)


        """2.构造规格选择仓库
        {(8, 11): 3, (8, 12): 4, (9, 11): 5, (9, 12): 6, (10, 11): 7, (10, 12): 8}
        """
        # 构造规格选择仓库
        temp_sku_qs = spu.sku_set.all()  # 获取当前spu下的所有sku
        # 选项仓库大字典
        spec_sku_map = {}  # {(8, 11): 3, (8, 12): 4, (9, 11): 5, (9, 12): 6, (10, 11): 7, (10, 12): 8}
        for temp_sku in temp_sku_qs:
            # 查询每一个sku的规格数据
            temp_spec_qs = temp_sku.specs.order_by('spec_id')
            temp_sku_option_ids = []  # 用来包装每个sku的选项值
            for temp_spec in temp_spec_qs:
                temp_sku_option_ids.append(temp_spec.option_id)
            spec_sku_map[tuple(temp_sku_option_ids)] = temp_sku.id


        """3.组合 并找到sku_id 绑定"""
        spu_spec_qs = spu.specs.order_by('id')  # 获取当前spu中的所有规格

        for index, spec in enumerate(spu_spec_qs):  # 遍历当前所有的规格
            spec_option_qs = spec.options.all()  # 获取当前规格中的所有选项
            temp_option_ids = current_sku_option_ids[:]  # 复制一个新的当前显示商品的规格选项列表
            for option in spec_option_qs:  # 遍历当前规格下的所有选项
                temp_option_ids[index] = option.id  # [8, 12]
                option.sku_id = spec_sku_map.get(tuple(temp_option_ids))  # 给每个选项对象绑定下他sku_id属性

            spec.spec_options = spec_option_qs  # 把规格下的所有选项绑定到规格对象的spec_options属性上

        context = {
            'categories': index_category(),  # 商品分类
            'breadcrumb': get_breadcrumb(category),  # 面包屑导航
            'sku': sku,  # 当前要显示的sku模型对象
            'category': category,  # 当前的显示sku所属的三级类别
            'spu': spu,  # sku所属的spu
            'spec_qs': spu_spec_qs,  # 当前商品的所有规格数据
        }
        print(spu_spec_qs)
        return render(request, 'detail.html', context)
# class VisitView(View):
#     def post(self,request,category_id):
#         category = GoodsCategory.objects.get(id=category_id)
#         try:
#             visit = GoodsVisitCount.objects.get(category_id=category_id)
#         except:
#
#             visit=GoodsVisitCount.objects.create(
#             category_id=category_id,count=0,)
#         visit.date=timezone.now()
#         visit.count+=1
#         visit.save()
class DetailVisitView(View):
    """商品类别每日访问量统计"""

    def post(self, request, category_id):

        try:
            # 校验category_id 是否真实存在
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseForbidden('商品类别不存在')

        # 获取当前日期
        # today_date = timezone.localdate()
        today_date = timezone.now()
        try:

            # 查询当前类别今天没有没统计过  # 注意不要写成data了
            count_data = GoodsVisitCount.objects.get(category=category, date=today_date)
        except GoodsVisitCount.DoesNotExist:
            # 如果当前类别今天是第一次来统计,就创建一个新记录,并给它指定是统计那一个类别
            count_data = GoodsVisitCount(
                category=category,

            )


        count_data.count += 1  # 累加浏览量
        count_data.save()


        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': "ok"})
# 商品浏览记录
class UserBrowseHistory(AuthenticateView):
    def get(self,request):
        skus=[]
        query_dict = request.GET
        # 获取用户
        user = request.user
        user_id=user.id
        conn =get_redis_connection('history')
    # pl = conn.pipeline()
        sku_list = conn.lrange('history_%s' % user_id,0,-1)
        for i in sku_list:
            sku = SKU.objects.get(id=i)
            sku.default_image_url=sku.default_image.url
            data={
                "name":sku.name,
                "default_image_url":sku.default_image.url,
                'price':sku.price,
                'id':sku.id
            }
            skus.append(data)
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","skus":skus})
    def post(self,request):
        query_str=request.body.decode()
        sku_id=json.loads(query_str).get("sku_id")
        if sku_id:
            user_id = request.user.id
            conn = get_redis_connection("history")
            pl = conn.pipeline()
            # 去重 列表中, 用户的键, 要采取的删除方式,要删除的值
            pl.lrem('history_%s' % user_id, 0, sku_id)
            pl.lpush('history_%s' % user_id,sku_id)
            pl.ltrim('history_%s' % user_id, 0, 4)
            pl.execute()
            return http.JsonResponse({'code':RETCODE.OK,'errmsg':"ok"})
        else:
            return  http.HttpResponseForbidden("非正常用户,非正常响应")
